package com.study.suanfa;

import java.util.*;

/**
 * @description: HashMapOrderTest  HashMap排序题
 * @date: 2020/11/11 12:33
 * @author: hcm
 * @version: 1.0
 */
public class HashMapOrderTest {
    public static void main(String[] args) {
        //向hashMap加入数据
        Map<Integer, User> map = new HashMap<>();
        map.put(4,new User(46,"嘛六"));
        map.put(1,new User(15,"张三"));
        map.put(9,new User(16,"李四"));
        map.put(2,new User(17,"王五"));
        //查看结果
       // map.forEach((i,j)-> System.out.println(i+"->"+"name->"+j.getName()+"->age->"+j.getAge()));

        //拿到map的键值对集合
        Set<Map.Entry<Integer, User>> entrySet = map.entrySet();

        //把键值对集合转list集合 ，利用集合工具类排序
        ArrayList<Map.Entry<Integer, User>> entryArrayList = new ArrayList<>(entrySet);

        //排序，出来的list是有序的
        Collections.sort(entryArrayList, new Comparator<Map.Entry<Integer, User>>() {
            @Override
            public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
                return o2.getValue().getAge() - o1.getValue().getAge();
            }
        });
        //查看有序list结果
        //System.out.println(entryArrayList);
        //结果无误

        //将list插入map，LinkedHashMap可以顺序插入
        LinkedHashMap<Integer , User> linkedHashMap = new LinkedHashMap();
        //遍历集合，把每一个entry加入map
        for (Map.Entry<Integer, User> userEntry : entryArrayList) {
            linkedHashMap.put(userEntry.getKey(),userEntry.getValue());
        }
        linkedHashMap.forEach((i,v)->{
            System.out.println("排好序后的结果-》"+i+"->age->"+v.getAge()+"->name->"+v.getName());
        });
    }
}
class  User{
    private int age ;
    private String name;

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
